<template>
  <el-dialog title="场景设置" :visible.sync="dialogTableVisible" @close="$emit('update:visible', false)" :modal-append-to-body="false">
    <el-form label-width="100px" label-position="left" ref="themeForm" :model="themeForm" :rules="rules">
      <el-form-item label="场景名称:" prop="themeName">
        <el-input v-model="themeForm.themeName" placeholder="请输入场景名称"></el-input>
      </el-form-item>
      <el-form-item label="开放状态:" prop="themeForm.status">
        <el-switch
          v-model="themeForm.status"
          active-color="#13ce66"
          inactive-color="#ff4949">
        </el-switch>
      </el-form-item>
      <el-form-item label="配置材料:" prop="materials">
        <el-select
          v-model="themeForm.materials"
          multiple
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="loading"
          @change="handleSelectChange"
          style="width: 100%;"
        >
          <el-option
            v-for="item in materialOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id+':'+item.name+':'+item.pic"
          >
          <span style="display: flex; align-items: center;">
            <img :src="item.pic" alt="material" style="width: 20px; height: 20px; margin-right: 10px;">
            {{ item.name }}
          </span>
          </el-option>
        </el-select>
        <el-pagination
          v-if="total > perPage"
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="perPage"
          :current-page="currentPage"
          @current-change="handlePageChange"
        ></el-pagination>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogTableVisible = false" size="small">取 消</el-button>
      <el-button type="primary" @click="submitForm" size="small">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import api from '@/utils/api.js'

export default {
  name: 'CornerTheme',
  props: ['visible'],
  watch: {
    'form.materials': function(newVal) {
      if (newVal !== null) {
        this.form.materials = this.materialOptions.find(option => option.id === newVal);
      }
    },
    visible() {
      this.dialogTableVisible = this.visible
      if (this.visible) {
        this.InitFn()
      }
    }
  },
  data() {
    return {
      dialogTableVisible: this.visible,
      themeForm: {
        themeName: '',
        status: false,
        materials: []
      },
      materialOptions: [],
      currentPage: 1,
      perPage: 20,
      total: 0,
      loading: false,
      searchKeyword: '',
      rules: {
        themeName: [
          { required: true, message: '请输入场景名称', trigger: 'blur' }
        ],
        materials: [
          { required: true, message: '请配置材料', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getMaterialList()
  },
  methods: {
    InitFn() {
      // 初始化表单数据，如果有需要
      this.themeForm = {
        themeName: '',
        status: false,
        materials: []
      }
      this.materialOptions = []
      this.currentPage = 1
      this.total = 0
      this.loading = false
      this.searchKeyword = ''
      this.getMaterialList()
    },
    getMaterialList(keyword = '') {
      if (this.loading) return
      this.loading = true
      this.$fetch(api.tools_index, { p: this.currentPage, limit: this.perPage, name: keyword }).then((response) => {
        if (response.code === 0) {
          this.materialOptions = response.list.data
          this.total = response.list.total
        } else {
          console.error('获取材料列表失败', response)
        }
      }).catch((err) => {
        console.error('获取材料列表错误', err)
      }).finally(() => {
        this.loading = false
      })
    },
    remoteMethod(keyword) {
      this.searchKeyword = keyword
      this.currentPage = 1
      this.getMaterialList(keyword)
    },
    handlePageChange(page) {
      this.currentPage = page
      this.getMaterialList(this.searchKeyword)
    },
    handleSelectChange(value) {
      // 处理 select 组件的 change 事件
      console.log('Select changed:', value)
    },
    submitForm() {
      this.$refs.themeForm.validate((valid) => {
        if (valid) {
          console.log('提交的数据：', this.themeForm)
          this.$emit('themeFormSubmit', this.themeForm)
          this.dialogTableVisible = false
        } else {
          console.log('表单验证失败')
          return false
        }
      })
    }
  }
}
</script>

<style>
.selectBox {
  width: 100%;
}
.pagination {
  margin-top: 10px;
  text-align: center;
}
</style>
